/* 
泛型接口
*/

 /* 
  1. 声明泛型类型: 在接口名的右侧  <T>   // T K V
  2. 使用泛型: 接口体中
  3. 指定泛型的具体类型: 定义实现时, 接口名的右侧 <具体类型>
  */

interface CRUD<T> {
  data: T[]
  add (t: T): number;
  getById(id: number): T
}

class User {
  id?: number
  name: string
  sex: string
  constructor (name, sex) {
    this.name = name
    this.sex = sex
  }
}

class UserCRUD implements CRUD<User> {
  data: User[] = []

  add (user: User): number {
    const id = Date.now()
    user.id = id
    this.data.push(user)

    return id
  }

  getById(id: number): User {
    return this.data.find(item => item.id === id)
  }
}

const userCRUD = new UserCRUD()
const id = userCRUD.add(new User('A', '男'))
userCRUD.add(new User('B', '女'))
console.log(userCRUD.data)
console.log(userCRUD.getById(id))